import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Select, Button, Badge, Divider, Modal } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './UserCert.less';

const confirm = Modal.confirm;
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'error', 'processing', 'success'];
const status = ['未审核', '未通过', '提现中', '提现成功'];

/* eslint react/no-multi-comp:0 */
@connect(({ appuser, loading }) => ({ appuser, loading: loading.models.appuser }))
@Form.create()
class UserWith extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
  };

  columns = [
    {
      title: '昵称',
      dataIndex: 'nick_name',
      key: 'nick_name',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '提现金额',
      dataIndex: 'money',
      key: 'money',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        {
          text: status[0],
          value: 0,
        },
        {
          text: status[1],
          value: 1,
        },
        {
          text: status[2],
          value: 2,
        },
        {
          text: status[3],
          value: 3,
        },
      ],
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '申请时间',
      dataIndex: 'created_at',
      key: 'created_at',
      sorter: true,
    },
    {
      title: '审核',
      render: (text, record) => (
        <Fragment>
          {record.status === 0 ? (
            <div>
              <a onClick={() => this.handleUpdateStatus(2, record)}>通过</a>
              <Divider type="vertical" />
              <a onClick={() => this.handleUpdateStatus(1, record)}>不通过</a>
            </div>
          ) : null}
          {record.status === 2 ? (
            <div>
              <a onClick={() => this.handleUpdateStatus(3, record)}>提现成功</a>
            </div>
          ) : null}
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'appuser/fetchUserWithDrawList' });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({ formValues: {} });
    dispatch({ type: 'appuser/fetchUserWithDrawList', payload: {} });
  };

  handleSelectRows = rows => {
    this.setState({ selectedRows: rows });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({ formValues: values });

      dispatch({ type: 'appuser/fetchUserWithDrawList', payload: values });
    });
  };

  handleUpdateStatus(status, record) {
    const { dispatch } = this.props;
    const values = {
      status: status,
      id: record.id,
    };

    let confirmContent = '';
    if (status === 1) {
      confirmContent = '确定要通过该用户的实名审核吗？';
    } else if (status === 2) {
      confirmContent = '确定要不通过该用户的实名审核吗？';
    } else {
      confirmContent = '确认提现成功，选择后则不可修改该!';
    }
    confirm({
      title: '提现',
      content: confirmContent,
      onOk() {
        dispatch({ type: 'appuser/fetchUserWithDrawStatus', payload: values });
      },
    });
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row
          gutter={{
            md: 8,
            lg: 24,
            xl: 48,
          }}
        >
          <Col md={8} sm={24}>
            <FormItem label="提现人">
              {getFieldDecorator('real_name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="提现人">
              {getFieldDecorator('real_name')(
                <Select>
                  <Option key={0}>待审核</Option>
                  <Option key={1}>未通过</Option>
                  <Option key={2}>提现中</Option>
                  <Option key={3}>已提现</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button
                style={{
                  marginLeft: 8,
                }}
                onClick={this.handleFormReset}
              >
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'appuser/fetchUserWithDrawList',
      payload: {
        page: params.current,
        pageSize: params.pageSize,
        sorter: params.sorter,
        status: params.status,
      },
    });
  };

  render() {
    const {
      appuser: { list },
      loading,
    } = this.props;
    const { selectedRows } = this.state;
    return (
      <PageHeaderWrapper title="提现审核">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              {selectedRows.length > 0 && (
                <span>
                  <Button>批量通过</Button>
                  <Button>批量不通过</Button>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={list}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default UserWith;
